const router = require('koa-router')()
const moment = require('moment')
const { Fb } = require('../class/utils')
const Attractions = require('../class/attractions')
const Upload = require('../class/upload')
const Db = require('../services/mysql')

router.prefix('/')

// 添加景区
router.post('/createAttr.do', Upload.upload.single('file'), async ctx => {
  const form = ctx.req.body
  form.img = 'images/' + ctx.req.file.filename //返回文件名
  let attrData = await Fb.callback(Attractions.create(form))
  if (attrData.status) {
    let KcrecordData = await Fb.callback(Attractions.createLibrary(attrData.data.id))
    if (KcrecordData.status) {
      ctx.body = Fb.success(attrData)
    } else {
      let KcreData = await Fb.callback(Attractions.delete(attrData.data))
      ctx.body = Fb.error('新增景区失败！')
    }
  } else {
    ctx.body = Fb.error('新增景区失败！')
  }
})

// 获取景区列表
router.post('/getAttrList.do', async ctx => {
  const form = ctx.request.body
  let nowPage = parseInt(form.nowPage) || 1
  let pageSize = parseInt(form.pageSize) || 9999999
  ctx.body = await Fb.callback(Attractions.select(form, nowPage, pageSize))
})

// 更新景区信息
router.post('/updateAttr.do', Upload.upload.single('file'), async ctx => {
  const form = ctx.req.body
  form.img = 'images/' + ctx.req.file.filename //返回文件名
  ctx.body = await Fb.callback(Attractions.update(form))
})

// 删除景区
router.post('/deleteAttr.do', async ctx => {
  const form = ctx.request.body
  let data = await Fb.callback(Attractions.delete(form))
  if(data.status){
    Attractions.delLibrary(form)
    ctx.body = Fb.success('删除成功！')
  }else{
    ctx.body = Fb.error('删除失败！')
  }
  //  ctx.body
})

//增加库存
router.post('/addLibrary.do', async ctx => {
  const form = ctx.request.body
  ctx.body = await Fb.callback(Attractions.addLibrary(form))
})

//获取轮播图
router.get('/getCarousel.do', async ctx => {
  ctx.body = await Fb.callback(Attractions.imgSelect())
})

module.exports = router
